package dobest.ray.com.jiongjiong.activity.action.service;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.os.Handler;
import android.util.SparseBooleanArray;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewGroup.MarginLayoutParams;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.dobest.ray.corelibs.utils.ToastMgr;
import com.dobest.ray.corelibs.views.NoScrollingGridView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import dobest.ray.com.jiongjiong.App;
import dobest.ray.com.jiongjiong.R;
import dobest.ray.com.jiongjiong.activity.BaseActivity;
import dobest.ray.com.jiongjiong.adapter.CityListAdapter;
import dobest.ray.com.jiongjiong.adapter.HotCitiesAdapter;
import dobest.ray.com.jiongjiong.bean.City;
import dobest.ray.com.jiongjiong.bean.PresenterData;
import dobest.ray.com.jiongjiong.callback.PresenterCallBack;
import dobest.ray.com.jiongjiong.utils.CityCreator;
import dobest.ray.com.jiongjiong.views.MyLetterView;
import dobest.ray.com.jiongjiong.views.NavigationBar;

/**
 * 选择城市
 * 
 * @Copyright Copyright © 2014 蓝色互动. All rights reserved.
 * 
 * @author wanglei
 * @Date: 2015-12-04
 */
@SuppressWarnings("rawtypes")
public class SelectCityActivity extends BaseActivity implements MyLetterView.OnTouchingLetterChangedListener, OnEditorActionListener,
		PresenterCallBack, OnClickListener/* , AMapLocationListener */ {
	/**
	 * 选择城市ListView
	 */
	private ListView cityListView;
	/**
	 * 字母提示
	 */
	private TextView overlay;
	/**
	 * 字母导航
	 */
	private MyLetterView letterView;
	private Handler handler;
	/**
	 * 隐藏字母导航的线程
	 */
	private OverlayThread ot;
	private WindowManager wm;
	/**
	 * 所有城市的列表
	 */
	private List<City> allCity;
	private List<City> hotCity;
	private List<City> result = new ArrayList<City>();
	/**
	 * 存储字母索引的哈希map
	 */
	private HashMap<String, Integer> alphaIndex;

	/**
	 * 头部布局
	 */
	private View header;

	/**
	 * 适配器
	 */
	private CityListAdapter adapter;

	/**
	 * 城市搜索
	 */
	private EditText et_search_city;
	private Context mContext;
	private LinearLayout ll_location_search;
	private NoScrollingGridView gv_hot_cities;
//	private HomePagePresenter presenter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_select_city);
		mContext = this;
		findViews();
		init();
		addListeners();
	}

	@Override
	public void findViews() {
		navi = (NavigationBar) findViewById(R.id.navbar);
		navi.setBackListener(this);
		// 得加入定位
		navi.setTitle("当前城市-" + App.getInstance().getCity());

	}

	@Override
	public void init() {
//		presenter = new HomePagePresenter(this);
		handler = new Handler();
		ot = new OverlayThread();
		// 从本地获取数据
		allCity = CityCreator.getSelectCities(getApplicationContext());
		Collections.sort(allCity, new CityComparator());

		result.addAll(allCity);
		initList();
		initOverlay();

		loadingDialog.show();
//		presenter.getHotCityList(this);
	}

	@Override
	public void addListeners() {
		et_search_city.setOnEditorActionListener(this);
		et_search_city.setOnFocusChangeListener(new OnFocusChangeListener() {

			@Override
			public void onFocusChange(View arg0, boolean flag) {
				if (flag) {
					ll_location_search.setVisibility(View.GONE);
					et_search_city.setHint("搜索");
					et_search_city.setFocusable(true);
					et_search_city.setFocusableInTouchMode(true);
					et_search_city.requestFocus();
				} else {
					ll_location_search.setVisibility(View.VISIBLE);
					et_search_city.setHint("");
				}

			}
		});

	}

	/**
	 * 初始化城市列表
	 * 
	 * @author ZhuFan
	 * @Package com.bm.zhengpinmao.activity
	 * @return void
	 * @throws @Date
	 *             2015-4-8 下午6:06:21
	 */
	@SuppressLint("InflateParams")
	private void initList() {
		header = LayoutInflater.from(this).inflate(R.layout.select_city_header, null);
		et_search_city = (EditText) header.findViewById(R.id.et_search_city);
		ll_location_search = (LinearLayout) header.findViewById(R.id.ll_location_search);
		letterView = (MyLetterView) findViewById(R.id.letter_view);
		letterView.setOnTouchingLetterChangedListener(this);

		cityListView = (ListView) findViewById(R.id.lv_cities);

		cityListView.addHeaderView(header);

		setCityListAdapter(cityListView);

		cityListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				if (position == 0)
					return;
				City city = result.get(position - 1);
				ToastMgr.show(city.name);
//				EventBus.getDefault().post(new EventBusBean("selected_city", city.name));
//				EventBus.getDefault().post(new EventBusCityBean("city_bean", city));
				finish();
			}
		});

		// initHeader();
	}

	@Override
	protected void onDestroy() {
		if (wm != null && overlay != null) {
			wm.removeViewImmediate(overlay);
		}
		super.onDestroy();
	}

	/**
	 * 初始化字母提示
	 * 
	 */
	@SuppressLint("InflateParams")
	private void initOverlay() {
		LayoutInflater inflater = LayoutInflater.from(this);
		overlay = (TextView) inflater.inflate(R.layout.select_city_overlay, null);
		overlay.setVisibility(View.INVISIBLE);

		WindowManager.LayoutParams lp = new WindowManager.LayoutParams(LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.TYPE_APPLICATION,
				WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
				PixelFormat.TRANSLUCENT);

		wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
		wm.addView(overlay, lp);
	}

	@Override
	public void onTouchingLetterChanged(final String s) {
		overlay.setText(s.substring(0, 1));
		overlay.setVisibility(View.VISIBLE);
		if (alphaIndex.get(s) != null) {
			int position = alphaIndex.get(s);
			cityListView.setSelection(position + 1);
		}
		handler.removeCallbacks(ot);
		handler.postDelayed(ot, 1000);
	}

	/**
	 * 隐藏字母提示
	 * 
	 */
	private class OverlayThread implements Runnable {
		@Override
		public void run() {
			overlay.setVisibility(View.GONE);
		}
	}

	private HotCitiesAdapter hotCityAdapter;

	/**
	 * 初始化城市列表
	 * 
	 */
	public void initHotCities() {
		gv_hot_cities = (NoScrollingGridView) header.findViewById(R.id.gv_hot_cities);
		hotCityAdapter = new HotCitiesAdapter(this, hotCity);
		gv_hot_cities.setAdapter(hotCityAdapter);
		gv_hot_cities.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View arg1, int position, long arg3) {
				hotCityAdapter.setSelected(position);
				ToastMgr.show(((City) parent.getAdapter().getItem(position)).name);
//				EventBus.getDefault()
//						.post(new EventBusBean("selected_city", ((City) parent.getAdapter().getItem(position)).name));
//
//				EventBus.getDefault()
//						.post(new EventBusCityBean("city_bean", ((City) parent.getAdapter().getItem(position))));
				finish();
			}
		});
	}

	/**
	 * 设置适配器
	 * 
	 */
	private void setCityListAdapter(ListView l) {
		adapter = new CityListAdapter(this, allCity);
		l.setAdapter(adapter);
		alphaIndex = adapter.getAlphaIndex();
	}

	public void setLetterViewHeight() {
		ViewTreeObserver vto = header.getViewTreeObserver();
		vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
			@SuppressWarnings("deprecation")
			@Override
			public void onGlobalLayout() {
				header.getViewTreeObserver().removeGlobalOnLayoutListener(this);
				int height = header.getHeight();
				MarginLayoutParams lp = (MarginLayoutParams) letterView.getLayoutParams();
				lp.topMargin = height;
				letterView.setLayoutParams(lp);
			}
		});
	}

	private TextView tv_city_name, tv_re_locate_hint, tv_re_locate;
	private ImageView iv_select_search;
	// private NoScrollingGridView gv_hot_cities;
	private LinearLayout ll_hot_city;

	// private void initHeader() {
	// tv_city_name = (TextView) header.findViewById(R.id.tv_city_name);
	// tv_re_locate_hint = (TextView)
	// header.findViewById(R.id.tv_re_locate_hint);
	// tv_re_locate = (TextView) header.findViewById(R.id.tv_re_locate);
	//
	// et_search = (EditText) header.findViewById(R.id.et_search);
	// iv_select_search = (ImageView)
	// header.findViewById(R.id.iv_select_search);
	// gv_hot_cities = (NoScrollingGridView)
	// header.findViewById(R.id.gv_hot_cities);
	//
	// ll_hot_city = (LinearLayout) header.findViewById(R.id.ll_hot_city);
	//
	// tv_re_locate.setOnClickListener(this);
	// iv_select_search.setOnClickListener(this);
	// gv_hot_cities.setOnItemClickListener(new OnItemClickListener() {
	// @Override
	// public void onItemClick(AdapterView<?> parent, View view, int position,
	// long id) {
	// City city = hotCity.get(position);
	// intent.putExtra("SELECTED_CITY", city);
	// setResult(RESULT_OK, intent);
	// SharedPreferencesHelper.getInstance(SelectCityActivity.this).setLocation(city.name);
	// SharedPreferencesHelper.getInstance(SelectCityActivity.this).setLocationId(city.id);
	// if (isStartUp) {
	// intent.setClass(SelectCityActivity.this, MainActivity.class);
	// startActivity(intent);
	// }
	// finish();
	//
	// }
	// });
	//
	// initMap();
	// setLocateCity();
	// handler.postDelayed(runnable, 15000);
	// }

	private void setLocateCity() {
//		String cityname = SharedPreferencesHelper.getInstance(this).getLocation();

		// if (isDuringLocate) {
		tv_re_locate_hint.setVisibility(View.GONE);
		tv_city_name.setVisibility(View.VISIBLE);
		tv_re_locate.setVisibility(View.GONE);

		tv_city_name.setText("定位中...");
		// } else {
		// if (isLocateFailed) {
		// tv_re_locate_hint.setVisibility(View.VISIBLE);
		// tv_city_name.setVisibility(View.GONE);
		// tv_re_locate.setVisibility(View.VISIBLE);
		// } else {
		// if (cityname == null || cityname.length() <= 0) {
		// tv_re_locate_hint.setVisibility(View.VISIBLE);
		// tv_city_name.setVisibility(View.GONE);
		// tv_re_locate.setVisibility(View.VISIBLE);
		// } else {
		// tv_re_locate_hint.setVisibility(View.GONE);
		// tv_city_name.setVisibility(View.VISIBLE);
		// tv_re_locate.setVisibility(View.VISIBLE);
		// tv_city_name.setText(cityname);
		// }
		// }
		// }
	}

	/**
	 * 排序
	 * 
	 * @Copyright Copyright © 2014 蓝色互动. All rights reserved.
	 * 
	 * @author ZhuFan
	 * @Date: 2014-12-11
	 */
	class CityComparator implements Comparator<City> {
		@Override
		public int compare(City lhs, City rhs) {
			String lhsString = lhs.first.substring(0, 1);
			String rhsString = rhs.first.substring(0, 1);
			return lhsString.compareTo(rhsString);
		}
	}

	private boolean relocateClicked;

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		// case R.id.tv_re_locate:
		// relocateClicked = true;
		// initMap();
		// setLocateCity();
		// handler.postDelayed(runnable, 15000);
		// break;
		// case R.id.iv_select_search:
		// String searchText = et_search.getText().toString().trim();
		// searchCity(searchText);
		// break;
		case R.id.ll_back_operate:
			finish();
			break;
		default:
			break;
		}
	}

	private void searchCity(String searchText) {
		loadingDialog.show();
		if (searchText.length() <= 0) {
			adapter.setList(allCity);
			ll_hot_city.setVisibility(View.VISIBLE);
		} else {
			SparseBooleanArray resultIndex = new SparseBooleanArray();
			result.clear();
			boolean isChinese = isChinese(searchText);
			for (City city : allCity) {
				if (isChinese) {
					if (city.name.indexOf(searchText) >= 0) {
						result.add(city);
					}
				} else {
					if (city.full.indexOf(searchText) >= 0) {
						if (!resultIndex.get(Integer.parseInt(city.id))) {
							result.add(city);
							resultIndex.put(Integer.parseInt(city.id), true);
						}
					}

					if (city.first.indexOf(searchText) >= 0) {
						if (!resultIndex.get(Integer.parseInt(city.id))) {
							result.add(city);
							resultIndex.put(Integer.parseInt(city.id), true);
						}
					}
				}
			}

			if (result.size() <= 0) {
				ToastMgr.show("暂无此城市", 2);
				loadingDialog.dismiss();
				return;
			}

			// ll_hot_city.setVisibility(View.GONE);
			adapter.setList(result);
			loadingDialog.dismiss();
		}
	}

	private boolean isChinese(String searchText) {
		Pattern p = Pattern.compile("[a-z A-Z]");
		Matcher m = p.matcher(searchText);
		if (m.find())
			return false;
		else
			return true;
	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	public boolean onEditorAction(TextView arg0, int actionId, KeyEvent event) {
		if ((event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
			searchCity(et_search_city.getText().toString());
			return true;
		}
		return false;
	}

	@Override
	public <T> void callBackPresenter(PresenterData<T> data) {
		T t = data.data;
		if ("Location_city".equals(data.tag)) {
			hotCity = ((List<City>) t);
			if (hotCity != null) {
				initHotCities();
			}
		}
		loadingDialog.dismiss();

	}

}
